package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 处理订单任务调度
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //处理超时订单的状态
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    public void processTimeoutOrder(){
        log.info("处理超时订单{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//plus是增加，Minutes是分钟，当前时间增加-15分钟就是减去15分钟
        List<Orders>  ordersList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        if(ordersList.size()>0&& ordersList!=null){
            for(Orders order:ordersList){
                order.setStatus(Orders.CANCELLED);//状态为已取消
                order.setCancelTime(LocalDateTime.now());//取消时间
                order.setCancelReason("订单超时，自动取消");//取消原因
                orderMapper.update(order);
            }
        }
    }

    //处理一直派送中的订单
    @Scheduled(cron = "0 * * * * ? ")//每分钟触发一次
    //@Scheduled(cron = "0 0 1 * * ?")//每天一点触发一次
    public void processDeliveryOrder(){
        log.info("处理一直派送的订单{}", LocalDateTime.now());

        List<Orders> ordersList = orderMapper.getByDeliveryOrder(Orders.DELIVERY_IN_PROGRESS);

        if(ordersList.size()>0&& ordersList!=null){
            for(Orders order:ordersList){
                order.setStatus(Orders.COMPLETED);//状态已完成
                orderMapper.update(order);
            }
        }
    }
}
